<template>
  <el-container class="me-top">
    <el-header>
      <el-row>
        <el-col :span="18" style="text-align: left;">
          <el-form ref="form" :model="formInline" :inline="true">
            <el-form-item label="名称:">
              <el-input v-model="formInline.name" />
            </el-form-item>
            <el-button icon="el-icon-search" circle @click="search" />
          </el-form>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" @click="add">添加订单</el-button>
          <el-popconfirm
            confirm-button-text="确认"
            cancel-button-text="取消"
            icon="el-icon-info"
            icon-color="red"
            title="确认全部删除？"
            @onConfirm="BatchRemove"
          >
            <el-button slot="reference" :disabled="flag" type="danger">删除订单</el-button>
          </el-popconfirm>
        </el-col>
      </el-row>
    </el-header>
    <el-main>
      <el-table :data="tableData" border stripe style="width: 100%" @selection-change="selectedRows">
        <el-table-column
          type="selection"
          width="55"
        />
        <el-table-column prop="id" label="订单编号" />
        <el-table-column prop="customerName" label="客户" />
        <el-table-column prop="status"  label="订单状态" align="center">
          <template slot-scope="scope">
            <el-tag :type="scope.row.status  ? 'success' : 'danger'">{{scope.row.status ? '已维修' :'维修中'}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="customerId" label="顾客ID" />
        <el-table-column prop="employee.username" label="维修员" />
        <el-table-column prop="createTime" label="创建时间" v-model="formInline.date"
                         type="date"
                         placeholder="选择日期"/>
        <el-table-column prop="setted"  label="是否结算" align="center">
          <template slot-scope="scope">
            <el-tag :type="scope.row.setted  ? 'info' : 'danger'">{{scope.row.setted ? '已结算' :'未结算'}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="250">
          <template slot-scope="scope">
            <el-button type="primary" :disabled="scope.row.setted" size="small" @click="edit(scope.row)">编辑</el-button>
            <el-popconfirm
              confirm-button-text="确认"
              cancel-button-text="取消"
              icon="el-icon-info"
              icon-color="red"
              title="你确定要删除当前数据？"
              @onConfirm="remove(scope.row)"
            >
              <el-button slot="reference" type="danger" size="small">删除</el-button>
            </el-popconfirm>
            <el-button type="info" :disabled="scope.row.setted" @click="settlement(scope.row)" size="small">结算订单</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="block">
        <el-pagination
          :page-sizes="pageSizes"
          :page-size="10"

          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
        <!-- :current-page="2"-->
      </div>
    </el-main>
    <!--  新增、编辑-->
    <el-dialog title="添加维修单" :visible.sync="dialogFormVisible" width="600px">
      <el-form ref="addForm" :model="addForm" label-width="100px" >
        <input v-model="addForm.id" type="hidden">
        <el-form-item prop="customer" label="客户名称" >
          <el-autocomplete
            v-model="state"
            :fetch-suggestions="querySearchAsync"
            placeholder="请输入内容"
            @select="handleSelect" />
        </el-form-item>
        <el-form-item prop="status" label="状态">
          <el-select v-model="addForm.status" placeholder="请选择" >
            <el-option v-for="item in statusOptions"
                       :key="item.value"
                       :label="item.label"
                       :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="employeeName" label="维修员" >
          <el-select v-model="addForm.employee.id" placeholder="请选择">
            <el-option v-for="item in employeeData"
                       :label="item.username"
                       :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="createTime" label="创建时间" >
          <div class="block">
            <span class="demonstration"/>
                <el-date-picker
                  v-model="addForm.createTime"
                  type="datetime"
                  format="yyyy-MM-ddHH:mm:ss"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  placeholder="选择日期"
                >
                </el-date-picker>
<!--            <el-date-picker v-model="addForm.createTime" type="date" placeholder="选择日期"-->
<!--                            format="yyyy-MM-dd HH:mm:ss">-->
<!--            </el-date-picker>-->
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </div>
    </el-dialog>

    <!--结算订单-->
    <el-dialog title="结算维修单" :visible.sync="settlementDialog">
      <el-form ref="settlementForm" :model="settlementForm" label-width="100px" >
        <el-form-item prop="customer" label="客户名称" >
            <el-input v-model="settlementForm.customer" :disabled="true"  />
        </el-form-item>
        <el-form-item prop="customer" label="应付金额" >
          <el-input v-model="settlementForm.reAmount" :disabled="true"  />
        </el-form-item>
        <el-form-item prop="reAmount" label="实付金额" >
          <el-input v-model="settlementForm.payAmount" :disabled="true" />
          <input type="hidden" v-model="settlementForm.repairorderId"/>
        </el-form-item>
        <el-form-item prop="pay" label="实付金额" >
          <el-select v-model="settlementForm.pay.id" placeholder="请选择">
            <el-option
              v-for="item in payData"
              :label="item.payment"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="settlementDialog = false">取 消</el-button>
        <el-button type="primary" @click="settlementSave">确 定</el-button>
      </div>
    </el-dialog>
  </el-container>

</template>

<script>
export default {
    data() {
        return {
            payData :[],
            settlementForm:{//结算表单
              customer:'',
              reAmount: '',
              payAmount: '',
              repairorderId : '',
              address:'',
              pay:{id:''}
            },
            settlementDialog : false,
            state: '',
            timeout:  null,
            //配件搜索框数组为（增改框）
            customerList: [],
          //维修员选择器数组（增改框）
            employeeData:[],
            customerData:[],
            statusOptions:[{
                key:'1',
                label:'维修中',
                value:false
            },{
                key:'2',
                label:'已维修',
                value:true
            }],
            customerIdOptions:[],
            employeeOptions:[],
            addForm: {
                id:'',
                customerName:'',
                status:'',
                customerId:'',
                employee:{
                    id:'',
                    username:''
                },
                createTime:''
            },
            flag: true,
            page: 1, // 第几页
            size: 10, // 每页条数
            total: 0,
            pageSizes: [5, 10, 15, 20],
            tableData: [],
            formInline: {
                name: '',
                date: ''
            },
            dialogFormVisible: false,
            selectRows: {}
            }
        },
        mounted() {
            this.loadListData()
            this.searchEmployee()
            this.searchPay()
            this.loadAll()
        },
        methods: {
            //------------------------------------结算单----------------------------------------------------------------------
            //------------------------------------结算单----------------------------------------------------------------------
            searchPay() {
              this.loading = true
              // vue加载完成，发送ajax请求动态获取数据
              this.$http.get('/pay/findAll').then((res) => {
                this.payData = res.data.data
              }).catch(error => {
                console.log(error)
              })
            },
            settlement(row){
              if(row.status){
                this.settlementDialog = true
                this.settlementForm.customer = row.customerName
                this.settlementForm.repairorderId = row.id
                this.$http.get('/repairorderitem/reAmountByRid/' + row.id).then((res) => {
                  this.settlementForm.reAmount = res.data
                })
                this.$http.get('/customer/findOne/' + row.customerId).then((res) => {
                  this.settlementForm.payAmount = (res.data.data.vip.discount * this.settlementForm.reAmount).toFixed(2)
                  this.settlementForm.address = res.data.data.address
                })
                console.log(this.settlementForm)
              }else {
                this.$notify({ title: '不能结算',  message: '维修单正在维修，请完成后再结算' ,  type: 'warning' });
              }

            },
            settlementSave(){
              this.$http.post('/setted/insert', this.settlementForm).then((res) => {
                if (res.data.success) {
                  this.$notify({ title: '结算成功',  message: res.data.message+'维修单已结算成功，到结算单管理查看详情' ,  type: 'success' });
                  this.settlementDialog = false
                  this.loadListData()
                }
              }).catch(error => {
                console.log(error)
              })
            },
            //------------------------------------结算单----------------------------------------------------------------------
            //------------------------------------结算单----------------------------------------------------------------------
          loadAll(){
            this.loading = true
            //格式化搜索框
            this.customerList = []
            // vue加载完成，发送ajax请求动态获取数据
            this.$http.get('/customer/findAll').then((res) => {
              const list = res.data.data
              //给搜索框赋值
              this.customerList = list.map((item) => {
                return {'value':item.name,
                  'id':item.id,
                }
              })
            }).catch(error => {
              console.log(error)
            })
          },

          //搜索框方法
          querySearchAsync(queryString, cb) {
            var customerList = this.customerList;
            var results = queryString ? customerList.filter(this.createStateFilter(queryString)) : customerList;

            clearTimeout(this.timeout);
            this.timeout = setTimeout(() => {
              cb(results);
            }, 1000 * Math.random());
          },
          //输入框搜索规则
          createStateFilter(queryString) {
            return (state) => {
              return (state.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
            };
          },
          //搜索框选中事件
          handleSelect(item) {
            //添加顾客Id
            this.addForm.customerId = item.id
            this.addForm.customerName= item.value
          },
            search() {
                this.loadListData()
            },
            submit() {
                if (this.addForm.id) { // 修改
                    this.$http.put('/repairorder/update', this.addForm).then((res) => {
                        if (res.data.success) {
                            this.$message.success(res.data.message)
                            this.loadListData()
                            this.dialogFormVisible = false
                        } else {
                            this.$message.error('修改失败[' + error.message + ']')
                        }
                    }).catch(error => {
                        console.log(error)
                    })
                } else { // 添加
                    this.$http.post('/repairorder/insert', this.addForm).then((res) => {
                        if (res.data.success) {
                            console.log(111)
                            this.$message.success(res.data.message)
                            this.loadListData()
                        } else {
                            console.log(2222)
                            // eslint-disable-next-line no-undef
                            this.$message.error('添加失败[' + error.message + ']')

                        }
                        this.dialogFormVisible = false
                    }).catch(error => {
                        console.log(error)
                    })
                }
            },
            add() {
                this.dialogFormVisible = true
                this.addForm.customerName = '';
                this.addForm.status = '';
                this.addForm.employee.name = '';
                this.addForm.createTime = '';
                this.updateVisible = true;
                this.addForm.id = ""
            },
            edit(row) {
                this.dialogFormVisible = true
                this.$nextTick(() => {
                    for (const key in row) {
                        this.addForm[key] = row[key]
                    }
                })
            },
            remove(row) {
                this.$http.delete('/repairorder/deleteById/' + row.id,{}).then(res => {
                    if (res.data.success) {
                        this.$message.success(res.data.message)
                        this.loadListData()
                    } else {

                        // eslint-disable-next-line no-undef
                        this.$message.error('删除失败[' + error.message + ']')
                    }
                }).catch(error => {
                    this.$message.error('删除失败[' + error.message + ']')
                })
            },
            BatchRemove() {
                const ids = this.selectRows.map(function(obj, index, arr) {
                    return obj.id
                })
                console.log(ids.toString())
                this.$http.post('/parts/batchDeleteById', { ids: ids }).then(res => {
                    if (res.data.success) {
                        this.$message.success(res.data.message)
                        this.loadListData()
                    } else {
                        // eslint-disable-next-line no-undef
                        this.$message.error('删除失败[' + error.message + ']')
                    }
                }).catch(error => {
                    this.$message.error('删除失败[' + error.message + ']')
                })
            },
            handleSizeChange(val) {
                this.size = val
                this.loadListData()
            },
            handleCurrentChange(currentPage) {
                this.page = currentPage
                this.loadListData()
            },
            loadListData() {
                this.loading = true
                // vue加载完成，发送ajax请求动态获取数据
                const param = {
                    'pageNo': this.page,
                    'pageSize': this.size,
                    'keyWord': this.formInline.name
                    // 'date': this.formInline.date
                }
                this.$http.post('/repairorder/findForList', param).then((res) => {
                    this.tableData = res.data.data.result
                    this.total = res.data.data.total
                    this.page = res.data.data.pageNo
                }).catch(error => {
                    console.log(error)
                })
            },
            searchEmployee() {
                this.loading = true
                // vue加载完成，发送ajax请求动态获取数据
                this.$http.get('/employee/findAll',{}).then((res) => {
                    this.employeeData = res.data.data
                }).catch(error => {
                    console.log(error)
                })
            },

            selectedRows(rows) {
                console.log(rows)
                if (rows.length > 0) {
                    this.flag = false
                    this.selectRows = rows
                } else {
                    this.flag = true
                }
            }
        }
    }
</script>

<style scoped>
  .me-top{
    padding-top: 20px;
  }
</style>
